package com.zls;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest
@RunWith(SpringRunner.class)
public class demo04 {
    @Autowired
    private TransportClient transportClient;

    @Autowired
    private ObjectMapper objectMapper;

    //查询所有
    @Test
    public void matchAllQuery() {
        //1.创建查询对象，设置查询条件，执行查询动作
        SearchResponse searchResponse = transportClient
                .prepareSearch("blog02")
                .setTypes("article")
//                .setQuery(QueryBuilders.matchAllQuery())
//                .setQuery(QueryBuilders.queryStringQuery("3").field("content"))
                .setQuery(QueryBuilders.matchQuery("title","机真"))
//                .setQuery(QueryBuilders.termQuery("title", "手机华为"))
//                .setSource(SearchSourceBuilder.searchSource().size(100))
                .get();
        //2.获取结果集
        SearchHits hits = searchResponse.getHits();
        TimeValue took = searchResponse.getTook();
        System.out.println("took:"+took);
        int successfulShards = searchResponse.getSuccessfulShards();
        System.out.println("获取分片数:"+successfulShards);
        System.out.println("获取到的总命中数：" + hits.getTotalHits());
        //3.遍历结果
        for (SearchHit hit : hits) {
            //queryStringQuery():字符串查询
            String sourceAsString = hit.getSourceAsString();
            System.out.println(sourceAsString);
        }
    }

}
